import {RouteLocationNormalized} from "vue-router";
import {BeforeEachReturnType, CustomRouterOptions, RouteListMode} from "./app-router-type";

export default async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    customRouterOptions: Required<CustomRouterOptions>
): Promise<BeforeEachReturnType> => {
  // loading
  if (
      typeof customRouterOptions.showLoading === "function"
          ? customRouterOptions.showLoading()
          : customRouterOptions.showLoading
  ) {
    customRouterOptions.showLoadingFunction();
  }
  customRouterOptions.afterShowLoading(to, from);


  const excludeList =
      typeof customRouterOptions.excludeList === "function"
          ? customRouterOptions.excludeList(to, from)
          : customRouterOptions.excludeList;

  // 名单中的路由
  if (customRouterOptions.routeListMode === RouteListMode.ALLOW) {
    if (excludeList.includes(to.path)) {
      return customRouterOptions.excludeListRouteForbidFunction(to, from);
    }
  }

  if (customRouterOptions.routeListMode === RouteListMode.BLOCK) {
    if (excludeList.includes(to.path)) {
      return customRouterOptions.excludeListRoutePermitFunction(to, from);
    }
  }

  // 非名单中的路由
  let nonInExcludeListRoutePermit =
      typeof customRouterOptions.nonInExcludeListRoutePermit === "function"
          ? customRouterOptions.nonInExcludeListRoutePermit(to, from)
          : customRouterOptions.nonInExcludeListRoutePermit;

  if (typeof nonInExcludeListRoutePermit !== "boolean") {
    nonInExcludeListRoutePermit = await nonInExcludeListRoutePermit;
  }

  if (nonInExcludeListRoutePermit) {
    return customRouterOptions.nonInExcludeRoutePermitFunction(to, from);
  }
  return customRouterOptions.nonInExcludeRouteForbidFunction(to, from);
};
